package com.starfactory.customer.handler;

import com.starfactory.common.shared.ResponseInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;


/**
 * 全局异常拦截器 给前端的接口默认都是用这个异常拦截器捕获
 */
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@Slf4j
@Order(2)
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    @ResponseStatus(value = HttpStatus.OK)
    public ResponseInfo sendError(Exception e) {
        log.error("服务异常", e);
        return ResponseInfo.fail("500", "服务异常");
    }

    @ExceptionHandler(value = IllegalArgumentException.class)
    @ResponseBody
    @ResponseStatus(value = HttpStatus.OK)
    public ResponseInfo handleIllegalArgumentException(Exception e) {
        log.error("IllegalArgumentException", e);
        return ResponseInfo.fail("参数校验失败", e.getMessage());
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    @ResponseStatus(value = HttpStatus.OK)
    public ResponseInfo handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error("MethodArgumentNotValidException", e);
        return ResponseInfo.fail("参数校验异常", e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
    }

}
